package com.study;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author MI
 * @ClassName FileChannelDemo1.java
 * @createTime 2021年09月09日 11:29:00
 */
public class FileChannelDemo1 {
    public static void main(String[] args) throws IOException {
        //创建FileChannel
        RandomAccessFile aFile = new RandomAccessFile("D:/desc.txt", "rw");
        FileChannel channel = aFile.getChannel();
        //创建buffer
        ByteBuffer buf = ByteBuffer.allocate(3);
        //读取数据到buffer中
        int bytesRead = channel.read(buf);

        while (bytesRead != -1) {
            System.out.println("读取了:" + bytesRead);
            //读写反转
            buf.flip();
            while (buf.hasRemaining()) {
                System.out.println((char) buf.get());
            }
            buf.clear();
            bytesRead = channel.read(buf);
        }
        aFile.close();
        System.out.println("finished");
    }
}
